<template>
	<div>
		<input id="uploadFile" ref="uploadFile" type="file" @change="uploadFile" class="hidden">
		<button type="button" @click="selectFile" class="btn btn-white btn-info btn-round">
			<i class="ace-icon fa fa-upload"></i>
			{{text}}
		</button>

	</div>
</template>

<script>
export default{
	name: 'bigFile',
	data() {
		return {
		}
	},
	props: {
		text: {
			default: '上传大文件'
		},
		suffixs: Array,
		uploadUrl: String,
		purpose: Number,
		afterUpload: Function
	},
	methods: {
		uploadFile() {
			
			let _this = this
			let file = this.$refs.uploadFile.files[0]
			if(!file) return
			let fileName = file.name
			let suffix = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length)
			let validSuffix = false
			this.suffixs.forEach(item=> {
				if(fileName.endsWith('.' + item)) {
					validSuffix = true
					return
				}
			})
			if(!validSuffix) {
				this.$toast("文件格式不正确,只支持文件格式:" + this.suffixs.join(','), this.$global.toast.warn)
				// 点击多次相同不合格文件都有提示
				this.$refs.uploadFile.value=null
				return
			}
			
			let shareSize = 5 * 1024 * 1024 //5MB
			let shareTotal = Math.ceil(file.size / shareSize)
			// 分片测试
			let shareIndex = 1//分片索引

			let key = hex_md5(file.name + file.size + file.type)
			let key62 = this.$global.format.tenTo62(parseInt(key, 16))

					
			// let formData = new window.FormData()
			// formData.append('file', fileShare)
			// formData.append('purpose', this.purpose)
			// formData.append('suffix', suffix)
			// formData.append('name', fileName)
			// formData.append('shareIndex', shareIndex + 1)
			// formData.append('shareTotal', shareTotal)
			// formData.append('shareSize', fileShare.size)
			// formData.append('shareKey', key62)
			
			let param = {
				'file': '',
				'purpose': _this.purpose,
				'suffix': suffix,
				'name': fileName,
				'size': file.size,
				'shareIndex': shareIndex,
				'shareTotal': shareTotal,
				'shareSize': shareSize,
				'shareKey': key62
			}

			this.checkShare(param)
			
		},
		checkShare(param) {
			let url = process.env.VUE_APP_SERVER + 'file/admin/file/check/' + param.shareKey
			this.$axios.post(url)
				.then(res => {
					let data = res.data
					if(data.status === 1){
						let fileDto = data.data
						if(!fileDto) {
							this.upload(param)
							console.log('没有找到文件记录，从分片1开始上传')
						}else {
							if(fileDto.shareIndex == fileDto.shareTotal){
								this.$toast('文件极速秒传成功', this.$global.toast.success)
								
								this.afterUpload(res.data)
								this.$refs.uploadFile.value=null
								return
							}
							this.$loading.show('文件上传中')
							param.shareIndex = fileDto.shareIndex + 1
							console.log('找到文件记录，从分片'+ param.shareIndex +'开始上传')
							this.upload(param)
							this.$loading.hide()
						}
					}else {
						this.$toast(res.data.msg, this.$global.toast.fail)
					}
				})
		},
		upload(param) {
			let _this = this
			let file = this.$refs.uploadFile.files[0]
			// 将文件转为base64位进行传输
			// readAsDataURL 方法会读取指定的 Blob 或 File 对象。
			// 读取操作完成的时候，readyState 会变成已完成DONE，并触发 loadend 事件，
			// 同时 result 属性将包含一个data:URL格式的字符串（base64编码）以表示所读取文件的内容。
			
			let shareIndex = param.shareIndex
			let shareTotal = param.shareTotal
			let shareSize = param.shareSize
			let fileShare = _this.getFileShare(shareIndex, shareSize, file)
			let fileReader = new FileReader()
			
			fileReader.onload = function(e) {
				let base64 = e.target.result
				param.file = base64
				param.shareSize = fileShare.size
				
				_this.$axios.post(_this.uploadUrl, param)
					.then(res => {
						if(res.data.status === 0) {
							_this.$toast(this.text + "失败", _this.$global.toast.fail)
							return
						}else if(shareIndex < shareTotal){
							// 上传下一个分片
							param.shareIndex = shareIndex + 1
							_this.upload(param, _this, file)
						}else{
							// 所有分片上传完
							_this.afterUpload(res.data)
							_this.$refs.uploadFile.value=null
						}
					})						
			}			
			
			fileReader.readAsDataURL(fileShare)
		},
		getFileShare(shareIndex, shareSize, file) {
			let start = (shareIndex - 1) * shareSize//分片起始未知
			let end = Math.min(start + shareSize, file.size)
			let fileShare = file.slice(start, end)
			return fileShare
		},
		
		selectFile() {
			// $('#uploadFile').trigger('click')
			this.$refs.uploadFile.click()
		}
	}
}
</script>

<style>
</style>
